/**
 * Created by tang on 2018/12/10.
 */
//react
import React, { Component, Fragment } from 'react';
import ReactDOM from 'react-dom';
//connect
import { connect } from 'dva';
//路由
import { routerRedux, Link } from 'dva/router';
//面包屑和title
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
//组件
import { Card, Button, Input, Select, Form, Row, Col, DatePicker, Divider,
  Popconfirm, message, Popover, Table, Badge, InputNumber, Modal } from 'antd';
//时间moment
import moment from 'moment';
//queryString
import queryString from 'query-string';
//权限
import { checks } from '@/utils/authority';
//样式
import styles from './ClassifySecond.less';

//const
const Option = Select.Option;
const Search = Input.Search;
const { RangePicker } = DatePicker;
const { TextArea } = Input;

//常量
//详情路由
const infoPath = '/classify/taskInfo';
const addPath = '/setting/classifyAdd';
//清楚model数据 方法
const clear = 'classify/clear';
//存数据
const save = 'classify/save';

//日常工作-列表
const list = 'classify/listSecond';
//删除
const del = 'classify/del';
//置顶
const sortType = 'classify/sort';
//审核
const state = 'classify/audit';

//权限
//列表
const checksList = '/admin/task/list';
//删除权限
const checksDel = '/admin/property/classify/del';
//修改权限
const checksUpdate = '/admin/property/classify/update';
//添加权限
const checksAdd = '/admin/property/classify/add';


//searchArray
const searchArray = [
  {value: 'name', label: '分类名'},
];
const initKey = 'name';


//其他
//标题
let title = '二级分类列表';
let status = [{title: '全部', status: 'default'}, {title: '审核中', status: 'warning'},  {title: '已通过', status: 'success'}, {title: '未通过', status: 'error'}];
let filters = [{text: '全部', value: '0'}, {text: '审核中', value: '1'},  {text: '已通过', value: '2'}, {text: '未通过', value: '3'}];

let statusArray = [{title: '全部', status: 'default'}, {title: '进行中', status: 'warning'},  {title: '已完成', status: 'success'}, {title: '已取消', status: 'error'}];
let filtersArray = [{text: '全部', value: '0'}, {text: '进行中', value: '1'},  {text: '已完成', value: '2'}, {text: '已取消', value: '3'}];

let typeFilters = [{text: '全部', value: '0'}, {text: '内部', value: '1'},  {text: '外部', value: '2'}];

@connect(state => ({
  classify: state.classify,
}))
@Form.create()
export default class ClassifySecond extends Component {

  state = {
    pageSize: 10, //页数

    addInputValue: '',
    modalVisible: false,
    expandForm: false,
    formValues: {},
    selectIndex: 0,
    id_1:0,
    //sort_default:0
    columns: [
      {
        title: '序号',
        dataIndex: 'index',
        width: '60px',
      },
      {
        key: 'name',
        title: '分类名',
        dataIndex: 'name',
      },
      {
        title: '创建时间',
        dataIndex: 'gmtCreate',
        render: (text) =><div>{moment(text).format('YYYY-MM-DD')}</div>
      },
      {
        title: '修改时间',
        dataIndex: 'gmtModified',
        render: (text) =><div>{moment(text).format('YYYY-MM-DD')}</div>
      },
      {
        title: '操作',
        key: 'do',
        fixed: 'right',
        width: 105,
        render: (record) => {
          let btns = [];
          if (checks(checksUpdate)){
            btns.push(
              <Link key="link" to={{pathname: addPath, search: '?id=' + record.id+'&pid='+this.state.pid+'&type=2'}}>编辑</Link>
            )
          }
          if(checks(checksDel)&&checks(checksUpdate)){
            btns.push(
              <Divider key="line" type="vertical" />
            );
          }
          if (checks(checksDel)){
            btns.push(
              <Popconfirm title="你确定要删除吗?" onConfirm={() => this.handleDelete(record.id)} onCancel={this.cancel}>
                <a href="#">删除</a>
              </Popconfirm>
            )

          }
          return(
            <div key="item">
              <Fragment>
                {btns}
              </Fragment>
            </div>
          )
        }
      }
    ],
    scrollX: 1000,
    visible: false,
    auditVisible: false,
    showReason: false,
    id: 0,
    pid:0
  };

  componentDidMount(){
    this.clear();
    this.networkRequest();
    var search = queryString.parse(this.props.location.search);
    this.setState({
      pid:search.pid
    });
  }
  //clear
  clear(){
    this.props.dispatch({
      type: clear
    });
  }
  //网络请求
  networkRequest(){
    var search = queryString.parse(this.props.location.search);
    const {dispatch} = this.props;
    dispatch({
      type:save,
      payload:{
        pid:search.pid
      }
    })
    dispatch({
      type: list,
      payload: {}
    })
  }

  /**
   * ********** 搜索开始 ************
   * */
  //返回搜索组件
  renderForm() {
    return this.renderSimpleForm();
  }
  //搜索组件
  renderSimpleForm() {
    const {classify: {loading}} = this.props;
    let searchDiv = [];
    let options = [];
    for (let i = 0; i < searchArray.length; i++){
      let item = searchArray[i];
      options.push(
        <Option value = {item.value} key = {item.value + i}>
          {item.label}
        </Option>
      )
    }
    searchDiv.push(
      <div key="search-key-have">
        <Row justify="start">
          <div className={styles.search_select_title}>
            <Select
              size="default"
              onSelect ={this.handleChange.bind(this)}
              defaultValue={initKey}
            >
              {options}
            </Select>
          </div>
          <div className={styles.search_select_value}>
            <Search
              placeholder="请输入关键字"
              onChange={this.querySearch.bind(this)}
            />
          </div>
        </Row>
        <div style={{height: '16px'}}></div>
        <Row>
          <div className={styles.sureBtn}>
            <Button onClick={this.searchAct.bind(this)}>确定</Button>
          </div>
        </Row>
        <div style={{height: '16px'}}></div>
      </div>
    );
    return(
      <Form>
        {searchDiv}
      </Form>
    )
  }
  //搜索框值变化
  querySearch(e){
    const { dispatch } = this.props;
    dispatch({
      type: save,
      payload: {searchValue: e.target.value}
    })
  }
  //搜索内容
  handleChange(value){
    const { dispatch } = this.props;
    dispatch({
      type: save,
      payload: {searchKey: value}
    })
  }
  //搜索
  searchAct(){
    const {dispatch} = this.props;

    dispatch({
      type: list,
      payload: {}
    })
  }
  /**
   * ********** 搜索结束 ************
   * */
  /**
   * table列表上方法 ******* 开始 **********
   * */
  //table变化
  handleTableChange(pagination, filters, sorter){
    const { dispatch } = this.props;
    let dic = {};
    if (filters.state){
      dic["state"] = filters.state[0] ? filters.state[0]: '0';
    }
    if (filters.status){
      dic["status"] = filters.status[0] ? filters.status[0]: '0';
    }
    if (filters.type){
      dic["type"] = filters.type[0] ? filters.type[0]: '0';
    }
    console.log(dic, filters);
    dispatch({
      type: save,
      payload: dic
    });
    this.networkRequest();
  }
  //table分页
  onShowSizeChange(page, pageSize){
    if (!page || !pageSize){
      return;
    }
    this.changePage(page, pageSize);
  }
  onPageChange(page, pageSize){
    if (!page || !pageSize){
      return;
    }
    this.changePage(page, pageSize);
  }
  changePage(page, pageSize){
    const { dispatch } = this.props;
    dispatch({
      type: save,
      payload: {
        page: page,
        pageSize: pageSize,
      }
    });
    this.networkRequest();
  }



  handleDelete(id) {
    const { dispatch } = this.props;
    dispatch({
      type: del,
      payload: {id: id},
      listType:2
    });
  }
  /**
   * 取消删除
   * */
  cancel(){
    message.error('您取消了删除!');
  }

  render() {
    //数据
    const { classify: {dataList, page, pageSize, total, sort, loading}} = this.props;

    /**
     * table配置 ********** 开始 ****************
     * data: 数据
     * pagination: 分页
     * */
    //数据 添加序号
    var data = [];
    if (dataList){
      for (let i = 0; i < dataList.length; i++){
        var item = dataList[i];
        let index = i + (page - 1) * pageSize + 1;
        item["index"] = index;
        data.push(item);
      }
    }
    //分页
    let pagination = {
      showQuickJumper: true,
      showSizeChanger: true,
      defaultCurrent: pageSize,
      total: total,
      pageSizeOptions: ['10', '20', '30', '40'],
      current: page,
      onShowSizeChange: this.onShowSizeChange.bind(this),
      onChange: this.onPageChange.bind(this),
      showTotal: (total) => ('共有' + total + '条数据')
    };
    /**
     * table配置 ********** 结束 ****************
     * */

    return (
      <PageHeaderWrapper title={title}>
        <Card bordered={false}>
          <div className={styles.tableList}>
            <div className={styles.tableListForm}>
              {
                this.renderForm()
              }
            </div>
            {
              checks(checksAdd)
                ?
                <div className={styles.tableListOperator} style={{marginBottom:30}}>
                  <Link to={{pathname: addPath, search: '?pid=' + this.state.pid+'&type=2'}}>
                    <Button icon="plus">新建</Button>
                  </Link>
                </div>
                : null
            }
            <Table
              columns={this.state.columns}
              //rowKey={record => record.login.uuid}
              dataSource={data}
              pagination={pagination}
              loading={loading}
              scroll={{ x: this.state.scrollX }}
              onChange={this.handleTableChange.bind(this)}
            />
          </div>
        </Card>
      </PageHeaderWrapper>
    );
  }
}

